<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="用户名/昵称/手机号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[100px]">
            <el-option :value="0" label="待审核" />
            <el-option :value="1" label="通过" />
            <el-option :value="2" label="未通过" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
            v-model="dateRange"
            :editable="false"
            class="!w-[240px]"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" highlight-current-row>
        <el-table-column label="用户名" prop="username" width="120" />
        <el-table-column label="昵称" width="120" align="center" prop="nickname" />
        <el-table-column label="性别" width="60" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.gender" code="gender" />
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
        <el-table-column label="审核状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus === 0" type="info" :disable-transitions="true">
              待审核
            </el-tag>
            <el-tag
              v-else-if="scope.row.auditStatus === 1"
              type="success"
              :disable-transitions="true"
            >
              已通过
            </el-tag>
            <el-tag
              v-else-if="scope.row.auditStatus === 2"
              type="danger"
              :disable-transitions="true"
            >
              未通过
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" prop="opinion" min-width="150" show-overflow-tooltip />
        <el-table-column label="审核人" align="center" prop="auditorName" width="120" />
        <el-table-column label="审核时间" align="center" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.auditTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.auditStatus === 0"
              type="primary"
              link
              @click="handleAudit(scope.row)"
            >
              审核
            </el-button>
            <el-button type="primary" link @click="handleHistory(scope.row)">历史</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 审核表单弹窗 -->
    <el-dialog
      v-model="auditDialog.visible"
      :title="auditDialog.title"
      width="500px"
      @close="auditDialog.visible = false"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditFormRules" label-width="100px">
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="opinion">
          <el-input
            v-model="auditForm.opinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核历史弹窗 -->
    <el-dialog
      v-model="historyDialog.visible"
      title="审核历史"
      width="800px"
      top="5vh"
      @close="historyDialog.visible = false"
    >
      <el-timeline class="pt-3 pb-3 h-[74vh] overflow-y-auto">
        <el-timeline-item
          v-for="(item, index) in historyList"
          :key="index"
          :timestamp="formatDateTime(item.auditTime)"
          :type="item.status === 1 ? 'success' : item.status === 2 ? 'danger' : 'info'"
        >
          <el-card class="mb-4">
            <div class="flex justify-between items-center mb-2">
              <div class="font-bold text-lg">
                <el-tag v-if="item.status === 0" type="info">待审核</el-tag>
                <el-tag v-else-if="item.status === 1" type="success">已通过</el-tag>
                <el-tag v-else-if="item.status === 2" type="danger">未通过</el-tag>
              </div>
              <div class="text-gray-500">审核人: {{ item.auditorName || "系统" }}</div>
            </div>
            <div class="text-gray-700">
              <div :class="{ 'line-clamp-2': !item.isExpanded }">
                {{ item.opinion || "无审核意见" }}
              </div>
              <el-button
                v-if="item.opinion && item.opinion.length > 100"
                type="primary"
                link
                class="mt-2"
                @click="item.isExpanded = !item.isExpanded"
              >
                {{ item.isExpanded ? "收起" : "展开" }}
              </el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div v-if="!historyList.length" class="text-center py-8 text-gray-500">暂无审核记录</div>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="咨询师详情"
      width="800px"
      top="5vh"
      @close="viewDialog.visible = false"
    >
      <div class="flex flex-col gap-4 h-[74vh] overflow-y-auto">
        <!-- 基本信息 -->
        <div>
          <h3 class="mb-3 text-lg font-bold">基本信息</h3>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="用户名">
              {{ consultantDetail.username }}
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              {{ consultantDetail.nickname }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              <DictLabel v-model="consultantDetail.gender" code="gender" />
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ consultantDetail.mobile }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ consultantDetail.email }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ consultantDetail.idCard || "未提供" }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 教育背景 -->
        <div>
          <h3 class="mb-3 text-lg font-bold">教育背景</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="学历">
              {{ consultantDetail.academicDegreeName }}
            </el-descriptions-item>
            <el-descriptions-item label="毕业院校">
              {{ consultantDetail.schoolName }}
            </el-descriptions-item>
            <el-descriptions-item label="专业">{{ consultantDetail.major }}</el-descriptions-item>
            <el-descriptions-item label="地址" :span="2">
              {{
                [
                  consultantDetail.provinceName,
                  consultantDetail.cityName,
                  consultantDetail.districtName,
                  consultantDetail.address,
                ]
                  .filter(Boolean)
                  .join(" ")
              }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 证书信息 -->
        <div>
          <h3 class="mb-3 text-lg font-bold">证书信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div v-if="consultantDetail.idCardFrontUrl" class="text-center">
              <p class="mb-2">身份证正面</p>
              <el-image
                :src="consultantDetail.idCardFrontUrl"
                :preview-src-list="[consultantDetail.idCardFrontUrl]"
                fit="cover"
                class="w-full h-48 object-contain border rounded"
              />
            </div>
            <div v-if="consultantDetail.idCardBackUrl" class="text-center">
              <p class="mb-2">身份证背面</p>
              <el-image
                :src="consultantDetail.idCardBackUrl"
                :preview-src-list="[consultantDetail.idCardBackUrl]"
                fit="cover"
                class="w-full h-48 object-contain border rounded"
              />
            </div>
            <div v-if="consultantDetail.degreeUrl" class="text-center">
              <p class="mb-2">学位证书</p>
              <el-image
                :src="consultantDetail.degreeUrl"
                :preview-src-list="[consultantDetail.degreeUrl]"
                fit="cover"
                class="w-full h-48 object-contain border rounded"
              />
            </div>
          </div>

          <!-- 其他证书 -->
          <div
            v-if="consultantDetail.otherUrl && consultantDetail.otherUrl.length > 0"
            class="mt-4"
          >
            <h4 class="mb-2 font-medium">其他资料</h4>
            <el-table :data="consultantDetail.otherUrl" border>
              <el-table-column label="文件名称" prop="fileName" min-width="150" />
              <el-table-column label="文件链接" min-width="200">
                <template #default="scope">
                  <el-link
                    v-if="scope.row.url"
                    type="primary"
                    :href="scope.row.url"
                    target="_blank"
                  >
                    {{ scope.row.url }}
                  </el-link>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.url"
                    type="primary"
                    link
                    size="small"
                    @click="window.open(scope.row.url || '', '_blank')"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 个人简介 -->
        <div>
          <h3 class="mb-3 text-lg font-bold">个人简介</h3>
          <div class="p-4 bg-gray-50 rounded">
            {{ consultantDetail.bio || "暂无个人简介" }}
          </div>
        </div>

        <!-- 擅长领域 -->
        <div v-if="consultantDetail.expertiseList && consultantDetail.expertiseList.length > 0">
          <h3 class="mb-3 text-lg font-bold">擅长领域</h3>
          <div class="flex flex-wrap gap-2">
            <el-tag
              v-for="(expertise, index) in consultantDetail.expertiseList"
              :key="index"
              type="success"
              effect="plain"
            >
              {{ typeof expertise === "string" ? expertise : expertise.name || expertise.dictCode }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onActivated } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  pageQuery,
  auditConsultant,
  getConsultantAuditHistory,
  getConsultantAudit,
} from "@/api/counselor-audit";
import type {
  ConsultantAuditPageQuery,
  ConsultantAuditPageVO,
  ConsultantAudit,
  ConsultantAuditVO,
} from "@/api/counselor-audit/type";
import { useUserStore } from "@/store";

defineOptions({
  name: "CounselorAudit",
});

// 查询表单ref
const queryFormRef = ref<FormInstance>();
// 审核表单ref
const auditFormRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);
// 总条数
const total = ref(0);
// 表格数据
const pageData = ref<ConsultantAuditPageVO[]>([]);
// Hooks: 日期范围
const dateRange = ref<[string, string]>();
const userInfo = useUserStore();

// 查询参数
const queryParams = reactive<ConsultantAuditPageQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  status: undefined,
  startDate: undefined,
  endDate: undefined,
});

// 计算属性：处理日期范围
const watchDateRange = computed({
  get: () => {
    if (queryParams.startDate && queryParams.endDate) {
      return [queryParams.startDate, queryParams.endDate] as [string, string];
    }
    return undefined;
  },
  set: (val) => {
    if (val) {
      queryParams.startDate = val[0];
      queryParams.endDate = val[1];
    } else {
      queryParams.startDate = undefined;
      queryParams.endDate = undefined;
    }
  },
});

// 审核表单对话框
const auditDialog = reactive({
  visible: false,
  title: "咨询师审核",
});

// 查看详情对话框
const viewDialog = reactive({
  visible: false,
});

// 历史记录对话框
const historyDialog = reactive({
  visible: false,
});

// 审核表单数据
const auditForm = reactive<ConsultantAudit>({
  consultantId: undefined as number | null | undefined,
  status: 1 as number, // 使用number类型
  opinion: "",
  auditorId: userInfo.userInfo.userId,
});

// 审核表单校验规则
const auditFormRules = reactive<FormRules>({
  status: [{ required: true, message: "请选择审核状态", trigger: "change" }],
  opinion: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
});

// 咨询师详情 - 扩展ConsultantAuditVO接口以包含UI显示需要的字段
const consultantDetail = ref<
  ConsultantAuditVO & {
    // 用于显示的额外字段
    provinceName?: string;
    cityName?: string;
    districtName?: string;
    address?: string;
    major?: string;
    bio?: string;
  }
>({});

// 历史记录列表
const historyList = ref<(ConsultantAudit & { isExpanded?: boolean })[]>([]);

/** 查询列表 */
function handleQuery() {
  loading.value = true;
  pageQuery({
    ...queryParams,
    startDate: dateRange.value?.[0],
    endDate: dateRange.value?.[1],
  })
    .then((res) => {
      console.log("API返回数据:", res); // 添加调试日志

      // 根据MyPageResult格式处理数据
      if (res.records) {
        pageData.value = Array.isArray(res.records) ? res.records : [res.records];
        total.value = res.total || 0;
      } else {
        pageData.value = [];
        total.value = 0;
        console.error("未识别的返回数据格式:", res);
      }
    })
    .catch((err) => {
      console.error("查询失败:", err);
      pageData.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询参数 */
function handleResetQuery() {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  dateRange.value = undefined;
  queryParams.pageNum = 1;
  handleQuery();
}

/** 查看咨询师详情 */
function handleView(row: ConsultantAuditPageVO) {
  viewDialog.visible = true;
  loading.value = true;
  getConsultantAudit(row.consultantId!)
    .then((res) => {
      consultantDetail.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查看审核历史 */
function handleHistory(row: ConsultantAuditPageVO) {
  historyDialog.visible = true;
  loading.value = true;
  getConsultantAuditHistory(row.consultantId!)
    .then((res) => {
      // 为每条记录添加展开状态
      historyList.value = res.map((item) => ({
        ...item,
        isExpanded: false,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 审核咨询师 */
function handleAudit(row: ConsultantAuditPageVO) {
  auditForm.consultantId = row.consultantId;
  auditForm.status = 1; // 默认选择通过
  auditForm.opinion = "";
  auditForm.id = row.id;
  auditDialog.visible = true;
}

/** 提交审核 */
function submitAudit() {
  if (!auditFormRef.value) return;

  auditFormRef.value.validate((valid) => {
    if (valid) {
      auditForm.auditorId = userInfo.userInfo.userId;
      auditForm.auditorName = userInfo.userInfo.nickname;
      loading.value = true;
      auditConsultant(auditForm)
        .then(() => {
          ElMessage.success("审核成功");
          auditDialog.visible = false;
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 添加时间格式化方法
/** 格式化时间 */
function formatDateTime(dateTimeStr: string | null | undefined): string {
  if (!dateTimeStr) return "";

  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    });
  } catch (e) {
    return dateTimeStr;
  }
}

// 页面加载时获取数据
onMounted(() => {
  handleQuery();
});

// 每次进入页面时重新查询数据
onActivated(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped></style>
